from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import Dict, Any
from datetime import datetime, timedelta

from app.core.database import get_db
from app.core.security import get_current_active_user
from app.models.user import User
from app.models.chat import ChatSession, ChatMessage
from app.models.release import Release
from app.models.analytics import UserBehavior, PageView, UserSession

router = APIRouter()

@router.get("/overview", summary="获取控制台概览数据")
async def get_dashboard_overview(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
) -> Dict[str, Any]:
    """
    获取控制台概览数据
    包括用户统计、聊天统计、发布统计等关键指标
    """
    
    # 获取时间范围（最近30天）
    end_date = datetime.utcnow()
    start_date = end_date - timedelta(days=30)
    last_month_start = start_date - timedelta(days=30)
    
    # 用户统计
    total_users = db.query(User).count()
    active_users = db.query(User).filter(User.is_active == True).count()
    new_users_this_month = db.query(User).filter(
        User.created_at >= start_date
    ).count()
    new_users_last_month = db.query(User).filter(
        User.created_at >= last_month_start,
        User.created_at < start_date
    ).count()
    
    # 计算用户增长率
    user_growth_rate = 0
    if new_users_last_month > 0:
        user_growth_rate = ((new_users_this_month - new_users_last_month) / new_users_last_month) * 100
    
    # 聊天统计
    total_chat_sessions = db.query(ChatSession).count()
    active_chat_sessions = db.query(ChatSession).filter(
        ChatSession.status == "active"
    ).count()
    total_messages = db.query(ChatMessage).count()
    messages_this_month = db.query(ChatMessage).filter(
        ChatMessage.created_at >= start_date
    ).count()
    
    # 发布统计
    total_releases = db.query(Release).count()
    successful_releases = db.query(Release).filter(
        Release.status == "success"
    ).count()
    pending_releases = db.query(Release).filter(
        Release.status == "pending"
    ).count()
    
    # 系统状态
    system_status = "正常"  # 这里可以根据实际监控数据来判断
    uptime_percentage = 99.9  # 这里可以从监控系统获取实际数据
    
    return {
        "user_stats": {
            "total_users": total_users,
            "active_users": active_users,
            "new_users_this_month": new_users_this_month,
            "user_growth_rate": round(user_growth_rate, 1)
        },
        "chat_stats": {
            "total_sessions": total_chat_sessions,
            "active_sessions": active_chat_sessions,
            "total_messages": total_messages,
            "messages_this_month": messages_this_month
        },
        "release_stats": {
            "total_releases": total_releases,
            "successful_releases": successful_releases,
            "pending_releases": pending_releases,
            "success_rate": round((successful_releases / total_releases * 100) if total_releases > 0 else 0, 1)
        },
        "system_stats": {
            "status": system_status,
            "uptime_percentage": uptime_percentage,
            "last_updated": datetime.utcnow().isoformat()
        }
    }

@router.get("/recent-activities", summary="获取最近活动")
async def get_recent_activities(
    limit: int = 10,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取最近的用户活动记录
    """
    activities = db.query(UserActivity).order_by(
        UserActivity.created_at.desc()
    ).limit(limit).all()
    
    return [
        {
            "id": activity.id,
            "user_id": activity.user_id,
            "action": activity.action,
            "module": activity.module,
            "description": activity.description,
            "created_at": activity.created_at.isoformat(),
            "user": {
                "username": activity.user.username,
                "full_name": activity.user.full_name
            } if activity.user else None
        }
        for activity in activities
    ]

@router.get("/system-metrics", summary="获取系统指标")
async def get_system_metrics(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取系统性能指标
    """
    # 获取最近的系统指标
    metrics = db.query(SystemMetrics).filter(
        SystemMetrics.timestamp >= datetime.utcnow() - timedelta(hours=24)
    ).order_by(SystemMetrics.timestamp.desc()).limit(100).all()
    
    # 按指标类型分组
    metrics_by_type = {}
    for metric in metrics:
        if metric.metric_name not in metrics_by_type:
            metrics_by_type[metric.metric_name] = []
        metrics_by_type[metric.metric_name].append({
            "value": metric.value,
            "timestamp": metric.timestamp.isoformat(),
            "unit": metric.unit
        })
    
    return metrics_by_type

@router.get("/quick-stats", summary="获取快速统计")
async def get_quick_stats(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取快速统计数据，用于仪表板卡片显示
    """
    today = datetime.utcnow().date()
    yesterday = today - timedelta(days=1)
    
    # 今日新增用户
    today_new_users = db.query(User).filter(
        User.created_at >= datetime.combine(today, datetime.min.time())
    ).count()
    
    # 今日活跃会话
    today_active_sessions = db.query(ChatSession).filter(
        ChatSession.last_message_at >= datetime.combine(today, datetime.min.time())
    ).count()
    
    # 今日消息数
    today_messages = db.query(ChatMessage).filter(
        ChatMessage.created_at >= datetime.combine(today, datetime.min.time())
    ).count()
    
    # 待处理发布
    pending_releases = db.query(Release).filter(
        Release.status == "pending"
    ).count()
    
    return {
        "today_new_users": today_new_users,
        "today_active_sessions": today_active_sessions,
        "today_messages": today_messages,
        "pending_releases": pending_releases,
        "timestamp": datetime.utcnow().isoformat()
    }